# -*- encoding: utf-8 -*-
from django.db import models
from django.db.models import signals
from django.template.defaultfilters import slugify


class Categoria(models.Model):
    nome = models.CharField(max_length=100)
    
    def __unicode__(self):
        return self.nome
    

class Noticia(models.Model):
    class Meta:
        ordering = ('data')
    
    data = models.DateTimeField(auto_now_add=True)
    titulo = models.CharField(max_length=100)
    resumo = models.CharField(max_length=250)
    descricao = models.TextField()
    url = models.ImageField(upload_to='fotos/%Y/%m/%d')
    categorias = models.ManyToManyField('Categoria', related_name='noticia_categoria')
    slug = models.CharField(max_length=100, blank=True, unique=True)   
    
    def __unicode__(self):
        return self.titulo
    
    class Meta():
        ordering = ('-data',)
        
        
def slug_pre_save(instance, sender, signal, *args, **kwargs):
    if not instance.slug:
        slug = slugify(instance.titulo)
        novo_slug = slug
        contador = 0
        
        while sender.objects.filter(slug=novo_slug).exclude(id=instance.id).count() > 0:
            contador +=1
            novo_slug = '%s-%d'%(slug, contador)
            
        instance.slug = novo_slug
        
signals.pre_save.connect(slug_pre_save, sender=Noticia)
